package cn.kennylee.codehub.springboot.microtrace.dubbo;

import cn.kennylee.codehub.springboot.microtrace.TraceContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.springframework.util.StringUtils;

import static cn.kennylee.codehub.springboot.microtrace.TraceUtils.getHeaderTraceIdName;


/**
 * Dubbo消费者链路追踪过滤器
 * <p>Created on 2025/5/7.</p>
 *
 * @author kennylee
 * @since 0.0.1
 */
@Activate(group = CommonConstants.CONSUMER, order = -10000)
@Slf4j
public class DubboTraceConsumerFilter implements Filter {

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {

        if (invocation.getAttachments().containsKey(getHeaderTraceIdName())) {
            // 如果请求头中已经存在 Trace ID，则直接返回
            log.info("请求头中已经存在 Trace ID: {}", invocation.getAttachment(getHeaderTraceIdName()));
            return invoker.invoke(invocation);
        }

        if (!StringUtils.hasLength(TraceContext.getTraceId())) {
            log.warn("找不到 Trace ID");
            return invoker.invoke(invocation);
        }

        // 设置Dubbo隐式参数
        invocation.setAttachment(getHeaderTraceIdName(), TraceContext.getTraceId());
        return invoker.invoke(invocation);
    }
}
